package com.fzz.learnitservice.component;

import com.commonfzz.tools.IdGenerator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 使用Redis缓存存储Ai对话记录
 */

@Component
@RequiredArgsConstructor
public class RedisChatMemory {

    private static final String KEY_PREFIX = "chat:memory:";
    private static final Duration EXPIRE_DURATION = Duration.ofDays(7);
    private static final int MAX_HISTORY_PAIRS = 10; // ✅ 最多保留10轮对话（即20条消息）

    private final RedisTemplate<String, Object> redisTemplate;


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ChatMessage implements Serializable {

        private String role; // "user" 或 "assistant"
        private String content; // 消息内容
        private LocalDateTime time; // 时间戳
        private long id;   // 唯一标识
    }

    /** 生成Redis Key */
    private String getKey(Long userId) {
        return KEY_PREFIX + (userId != null ? userId : "unknown");
    }

    /** 获取历史消息 */
    @SuppressWarnings("unchecked")
    public List<ChatMessage> getHistory(Long userId) {
        Object obj = redisTemplate.opsForValue().get(getKey(userId));
        if (obj == null) return new ArrayList<>();

        List<ChatMessage> result = new ArrayList<>();

        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                if (o instanceof ChatMessage) {
                    result.add((ChatMessage) o);
                } else if (o instanceof Map) {
                    Map<String, Object> map = (Map<String, Object>) o;
                    ChatMessage msg = new ChatMessage();
                    msg.setRole((String) map.get("role"));
                    msg.setId((Long) map.get("id"));
                    msg.setContent((String) map.get("content"));
                    Object time = map.get("time");
                    if (time != null) msg.setTime(LocalDateTime.parse(time.toString()));
                    result.add(msg);
                }
            }
        }
        return result;
    }


    /** ✅ 保存问答消息（保留最新10轮） */
    public void saveMessage(String question, String answer, Long userId) {
        String redisKey = this.getKey(userId);
        List<ChatMessage> history = getHistory(userId);
        IdGenerator idGenerator = new IdGenerator(12);

        // 添加新消息
        history.add(new ChatMessage("user", question, LocalDateTime.now(), idGenerator.nextId()));
        history.add(new ChatMessage("assistant", answer, LocalDateTime.now(), idGenerator.nextId()));

        // ✅ 限制最多保存 10 轮（即 20 条消息）
        if (history.size() > MAX_HISTORY_PAIRS * 2) {
            int fromIndex = history.size() - MAX_HISTORY_PAIRS * 2;
            history = new ArrayList<>(history.subList(fromIndex, history.size())); // 保留最新消息
        }

        // 存入Redis并设置过期时间
        redisTemplate.opsForValue().set(redisKey, history, EXPIRE_DURATION.toSeconds(), TimeUnit.SECONDS);
    }

    /** 清空会话 */
    public void clear(Long userId) {
        redisTemplate.delete(getKey(userId));
    }
}